package com.ebanma.cloud.usertestall.util;


import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;


/**
 * 验证器工具类
 *
 * @author liuhe41
 * @date 2023/03/24
 */
public class ValidatorUtil {
    /**
     * 验证器
     */
    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> void validate(T object, Class... groups) {
        //返回校验结果
        Set<ConstraintViolation<T>> validate = validator.validate(object, groups);

        //如果校验结果不为空
        if (!CollectionUtils.isEmpty(validate)) {
            StringBuilder stringBuilder = new StringBuilder();
            validate.forEach(result -> stringBuilder.append(result.toString()));

            throw new RuntimeException(stringBuilder.toString());
        }
    }
}
